package cn.com.platform.web.manage.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.com.easy.exception.BusinessException;
import cn.com.easy.permission.model.UserModel;
import cn.com.easy.permission.service.system.urlreserve.anotion.UrlReserveAnotion;
import cn.com.easy.permission.web.controller.BaseController;
import cn.com.easy.permission.web.dto.MessageDTO;
import cn.com.easy.permission.web.dto.PageRequestParamDTO;
import cn.com.easy.utils.FastJSONUtils;
import cn.com.easy.utils.Page;
import cn.com.easy.utils.PageRequest;
import cn.com.easy.utils.PageUtils;
import cn.com.easy.utils.ResponseOutputUtils;
import cn.com.platform.dao.ArticleCateDao;
import cn.com.platform.dao.ArticleDao;
import cn.com.platform.dao.BlockDao;
import cn.com.platform.entity.AccessoryEntity;
import cn.com.platform.entity.ArticleCateEntity;
import cn.com.platform.entity.ArticleEntity;
import cn.com.platform.entity.BlockEntity;
import cn.com.platform.mybatis.ArticleMybatisDao;
import cn.com.platform.service.ArticleService;
import cn.com.platform.service.BlockItemService;
import cn.com.platform.utils.FileUtils;
import cn.com.platform.web.manage.dto.ArticleDto;
import cn.com.platform.web.manage.dto.ArticleQueryParamDto;
import cn.com.platform.web.manage.dto.BlockItemDto;

import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;

/**
 * 文章管理
 * 
 * @author nibili 2018年7月17日
 * 
 */
@Controller
@RequestMapping("/manage/article")
public class ArticleManageController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(ArticleManageController.class);

	/** 文章分类dao */
	@Autowired
	private ArticleCateDao articleCateDao;

	/** 文章dao */
	@Autowired
	private ArticleDao articleDao;

	/** 文章mybatis dao */
	@Autowired
	private ArticleMybatisDao articleMybatisDao;

	/** 推荐位Dao */
	@Autowired
	private BlockDao blockDao;

	/** 文章服务类 */
	@Autowired
	private ArticleService articleService;

	/** 内容推荐服务类 */
	@Autowired
	private BlockItemService blockItemService;

	/** UEditor 图片上传等控制器 */
	@Autowired
	private UEditorManagerController uEditorManagerController;

	@UrlReserveAnotion("文章管理首页")
	@RequestMapping("")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "/manage/article/article";
	}

	/**
	 * 文章 搜索
	 * 
	 * @param req
	 * @param res
	 * @param paramDto
	 * @param param
	 * @author wxy 2016年8月3日
	 */
	@UrlReserveAnotion("文章管理列表")
	@RequestMapping("/list")
	public void list(HttpServletRequest req, HttpServletResponse res, PageRequestParamDTO paramDto, final ArticleQueryParamDto param) {
		if (StringUtils.isEmpty(paramDto.getSortName())) {
			paramDto.setSortName("orderby");
			paramDto.setSortOrder("desc");
		}
		PageList<ArticleDto> pageObject = articleMybatisDao.queryArticles(param, paramDto.buildMyBatisPageRequest());
		Page<ArticleDto> page = PageUtils.getPage(pageObject);
		ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", true, page));
	}

	/**
	 * 添加或更新文章
	 * 
	 * @param request
	 * @param response
	 * @param articleCateTreeDto
	 * @author wxy 2016年8月9日
	 */
	@UrlReserveAnotion("添加或更新文章")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void saveOrUpdateArticle(HttpServletRequest request, HttpServletResponse response, ArticleDto articleDto, MultipartFile file) throws Exception {
		try {
			UserModel user = getCurrentUser(request);
			if (user == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			if (file != null && file.getSize() > 0) {
				articleDto.setPhoto(FileUtils.picUpload(file, "photo/art/thumbnail", this.getCurrentUser(request).getId()));
			}
			articleService.saveOrUpdate(articleDto, user, Long.valueOf(request.getSession().getId().hashCode()));
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
		} catch (Exception ex) {
			logger.error("添加或更新添加或更新文章分类异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "添加或更新文章异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 删除文章
	 * 
	 * @param req
	 * @param res
	 * @param articlesId
	 * @author wxy 2016年8月3日
	 */
	@UrlReserveAnotion("删除文章")
	@RequestMapping("/delete")
	public void deleteArticles(HttpServletRequest req, HttpServletResponse res, ArticleEntity articleEntity) {
		try {
			UserModel user = getCurrentUser(req);
			if (user == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			if (articleEntity.getId() == null) {
				throw new BusinessException("未找到该文章");
			}
			ArticleEntity articleEntityTemp = articleDao.findByIdAndTitle(articleEntity.getId(), articleEntity.getTitle());
			if (articleEntityTemp == null) {
				throw new BusinessException("未找到该文章");
			} else {
				articleEntityTemp.setDeleteStatus(true);
				articleEntityTemp.setLastModifyBy(user.getLoginname());
				articleEntityTemp.setLastModifyTime(new Date());
				articleDao.save(articleEntityTemp);
				ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", true, "删除成功"));
			}
		} catch (BusinessException ex) {
			ResponseOutputUtils.renderJson(res, FastJSONUtils.toJsonString(MessageDTO.newInstance("", false, ex.getMessage())));
		} catch (Exception ex) {
			logger.error("删除文章错误：", ex);
			ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", false, ex.getMessage()));
		}
	}

	/**
	 * 关闭/开启文章
	 * 
	 * @param req
	 * @param res
	 * @param articlesId
	 * @author wxy 2016年8月29日
	 */
	@UrlReserveAnotion("关闭/开启文章")
	@RequestMapping("/close")
	public void closeArticles(HttpServletRequest req, HttpServletResponse res, ArticleEntity articleEntity) {
		try {
			UserModel user = getCurrentUser(req);
			if (user == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			if (articleEntity.getId() == null) {
				throw new BusinessException("未找到该文章");
			}
			ArticleEntity articleEntityTemp = articleDao.findByIdAndTitle(articleEntity.getId(), articleEntity.getTitle());
			if (articleEntityTemp == null) {
				throw new BusinessException("未找到该文章");
			} else {
				if (articleEntityTemp.getClosed() == true) {
					articleEntityTemp.setClosed(false);
				} else {
					articleEntityTemp.setClosed(true);
				}
				articleEntityTemp.setLastModifyBy(user.getLoginname());
				articleEntityTemp.setLastModifyTime(new Date());
				articleDao.save(articleEntityTemp);
				ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", true, ""));
			}
		} catch (BusinessException ex) {
			ResponseOutputUtils.renderJson(res, FastJSONUtils.toJsonString(MessageDTO.newInstance("", false, ex.getMessage())));
		} catch (Exception ex) {
			logger.error("关闭文章错误：", ex);
			ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", false, ex.getMessage()));
		}
	}

	// 获取文章分类
	/**
	 * 获取所有文章分类
	 * 
	 * @param request
	 * @param response
	 * @param pageRequestParamDTO
	 * @author wxy 2016年8月3日
	 */
	@UrlReserveAnotion("获取所有文章分类")
	@RequestMapping("/get/allCate")
	public void getAllCate(HttpServletRequest request, HttpServletResponse response, PageRequestParamDTO pageRequestParamDTO) {
		try {

			pageRequestParamDTO.setPageSize(10000);
			if (StringUtils.isBlank(pageRequestParamDTO.getSortName()) == true) {
				pageRequestParamDTO.setSortName("orderby");
				pageRequestParamDTO.setSortOrder("asc");
			}
			org.springframework.data.domain.Page<ArticleCateEntity> catePage = articleCateDao.findByDeleteStatusAndHidden(pageRequestParamDTO.buildSpringDataPageRequest(), false,
					false);
			// 结构调整
			if (CollectionUtils.isNotEmpty(catePage.getContent()) == true) {
				Table<Long, Long, ArticleCateEntity> tables = HashBasedTable.create();
				for (ArticleCateEntity articleCateEntity : catePage.getContent()) {
					if (articleCateEntity.getParentId() == null || articleCateEntity.getParentId() == 0) {
						tables.put(articleCateEntity.getId(), -1l, articleCateEntity);
					} else {
						tables.put(articleCateEntity.getId(), articleCateEntity.getParentId(), articleCateEntity);
					}
				}
				// 结果集，根节点
				List<ArticleCateEntity> resultList = Lists.newArrayList();
				List<ArticleCateEntity> rootList = Lists.newArrayList(tables.column(-1l).values());
				Long addNum = (long) 0;
				for (ArticleCateEntity articleCateEntity : rootList) {
					addNum++;
					this.getTreeList(Long.toString(addNum), articleCateEntity, resultList, tables);
				}
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, resultList));
			}

		} catch (Exception ex) {
			logger.error("获取所有文章分类异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取所有文章分类异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 查找给定元素的子元素
	 * 
	 * @param articleCateEntity
	 * @param tables
	 * @return
	 * @auth nibili 2016年6月10日 上午12:02:25
	 */
	private void getTreeList(String nameStart, ArticleCateEntity articleCateEntity, List<ArticleCateEntity> result, Table<Long, Long, ArticleCateEntity> tables) {
		articleCateEntity.setTitle(nameStart + "-" + articleCateEntity.getTitle());
		result.add(articleCateEntity);
		// 查找子集
		List<ArticleCateEntity> list = Lists.newArrayList(tables.column(articleCateEntity.getId()).values());
		if (CollectionUtils.isNotEmpty(list) == true) {
			for (int i = 0, len = list.size(); i < len; i++) {
				ArticleCateEntity articleCateEntityTemp = list.get(i);
				getTreeList("　" + nameStart + "." + (i + 1), articleCateEntityTemp, result, tables);
			}
		}
	}

	/**
	 * 获取推荐位
	 * 
	 * @param request
	 * @param response
	 * @author wxy 2016年8月25日
	 */
	@UrlReserveAnotion("获取推荐位")
	@RequestMapping(value = "/blockItem/findBlock")
	public void getAllBlock(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<BlockEntity> blockPageEntities = blockDao.findByDeleteStatus(false);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, blockPageEntities));
		} catch (Exception ex) {
			logger.error("获取推荐位异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取推荐位异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 保存或更新内容推荐
	 * 
	 * @param request
	 * @param response
	 * @param BlockItemDto
	 * @author wxy 2016年8月17日
	 */
	@UrlReserveAnotion("保存文章推荐")
	@RequestMapping(value = "/blockItem/save", method = RequestMethod.POST)
	public void blockItemSave(HttpServletRequest request, HttpServletResponse response, BlockItemDto blockItemDto) {
		try {
			UserModel user = getCurrentUser(request);
			if (user == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			if (blockItemDto.getItemId() == null || blockItemDto.getItemId() <= 0) {
				throw new BusinessException("未找到文章");
			}
			ArticleEntity articleEntity = articleDao.findOne(blockItemDto.getItemId());
			if (articleEntity.getAudit() == false) {
				throw new BusinessException("文章审核未通过");
			}
			if (articleEntity.getClosed() == true) {
				throw new BusinessException("文章为关闭状态");
			}
			// 获取文章标题
			blockItemDto.setTitle(articleEntity.getTitle());

			blockItemDto.setLink(articleEntity.getLinkurl());
			blockItemService.saveBlockItem(blockItemDto, user);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, "保存文章推荐成功"));
		} catch (Exception ex) {
			logger.error("提交文章推荐信息异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交文章推荐信息异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/**
	 * 进入图片上传页面
	 * 
	 * @param modelMap
	 * @param req
	 * @param res
	 * @return
	 * @auth nibili 2018年7月16日
	 */
	@UrlReserveAnotion("进入添加图片页面")
	@RequestMapping("/photo_add")
	public String addPhotoPre(ModelMap modelMap, HttpServletRequest req, HttpServletResponse res) {

		return uEditorManagerController.addPhotoPre(modelMap, req, res);
	}

	/**
	 * 编辑器选择图片
	 * 
	 * @param modelMap
	 * @param req
	 * @param res
	 * @param pageRequest
	 * @param albumId
	 *            相册id，也是文章id
	 * @return
	 * @throws BusinessException
	 * @auth nibili 2018年7月16日
	 */
	@UrlReserveAnotion("编辑器选择图片")
	@RequestMapping("/photo_select")
	public String selectImg4editor(ModelMap modelMap, HttpServletRequest req, HttpServletResponse res, PageRequest pageRequest, Long albumId) {
		if (albumId == null) {
			albumId = Long.valueOf(req.getSession().getId().hashCode());
		}
		return uEditorManagerController.selectImg4editor(modelMap, req, res, pageRequest, AccessoryEntity.MODULE_ID_ENUM.MODULE_ID_ARTICLE.getValue(), albumId);
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 * @param req
	 * @param res
	 * @param articleId
	 * @throws Exception
	 * @auth nibili 2018年7月16日
	 */
	@UrlReserveAnotion("上传文件")
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public void uploadFile(@RequestParam(value = "file") MultipartFile[] file, HttpServletRequest req, HttpServletResponse res, Long albumId) {
		if (albumId == null) {
			albumId = Long.valueOf(req.getSession().getId().hashCode());
		}
		uEditorManagerController.uploadFile(file, req, res, AccessoryEntity.MODULE_ID_ENUM.MODULE_ID_ARTICLE.getValue(), albumId);
	}

}
